<template>
  <div>
    <BasePage>
      <el-card>
        <el-row class="diy-row" :gutter="12">
          <el-col :span="2">
            <el-button type="primary" @click="showCreateUserDialog">添加用户</el-button>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入内容" v-model="query" clearable @clear="removeSearch">
              <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
            </el-input>
          </el-col>
        </el-row>
        <el-table :data="userList" style="width: 100%" border>
          <el-table-column prop="username" label="用户" width="180"> </el-table-column>
          <el-table-column prop="nick_name" label="昵称" width="180"> </el-table-column>
          <el-table-column prop="mobile" label="手机"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="role_name" label="角色" width="180"> </el-table-column>
          <el-table-column prop="status" label="状态" width="70">
            <template scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#ff4949"
                @change="changeStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="操作" width="120">
            <template scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="showEditUserDialog(scope.row.id)"
              ></el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 添加/编辑用户 dialog -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="userInfoDialogVisible"
        width="35%"
        @close="closeDialog"
      >
        <el-form :model="userInfoForm" :rules="userRules" ref="userInfoRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfoForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select clearable v-model="userInfoForm.role" placeholder="请选择用户角色">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="昵称" v-if="createUserInfo === false">
            <el-input v-model="userInfoForm.nick_name" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfoForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userInfoForm.mobile" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="createUserInfo === true">
            <el-input
              placeholder="请输入密码"
              show-password
              v-model="userInfoForm.password"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userInfoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="createOrEditUser">确 定</el-button>
        </span>
      </el-dialog>
    </BasePage>
  </div>
</template>

<script>
export default {
  data() {
    var checkUsername = (rule, value, cb) => {
      const regName = /^[a-zA-Z0-9_]{3,20}$/
      if (regName.test(value)) {
        cb()
      }
      cb(new Error('用户名只允许输入3至20位字母、数字、_'))
    }
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[0-9a-zA-Z_.-]+@[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*\.[0-9a-zA-Z-]{2,6}$/
      if (regEmail.test(value)) {
        cb()
      }
      cb(new Error('请输入合法邮箱地址'))
    }

    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[356789]\d{9}$/
      if (regMobile.test(value)) {
        cb()
      }
      cb(new Error('请输入合法手机号'))
    }
    return {
      userList: [],
      userInfoDialogVisible: false,
      userInfoForm: {
        id: 0,
        username: '',
        nick_name: '',
        email: '',
        mobile: '',
        password: '',
        status: '',
        role: ''
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 8, max: 20, message: '长度在 8 到 20 个字符', trigger: 'blur' }
        ],
        role: [{ required: true, message: '请选择用户角色', trigger: 'change', type: 'number' }]
      },
      dialogTitle: '',
      createUserInfo: true,
      query: '',
      roleList: []
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    getUserList() {
      this.$http
        .get('/auth/list')
        .then(res => {
          const resData = res.data
          if (resData.code === 200) {
            this.userList = resData.data.list
          } else {
            this.$message.error('获取数据失败')
          }
        })
        .catch(err => {
          this.$message.error(err)
        })
    },
    // 修改用户状态
    changeStatus(userInfo) {
      this.$http
        .get(`/auth/changStatus?id=${userInfo.id}`)
        .then(res => {
          const resData = res.data
          if (resData.code === 200) {
            // userInfo.status = userInfo.status
            return this.$message.success('用户状态更新成功')
          } else {
            userInfo.status = !userInfo.status
            return this.$message.error('用户状态更新失败')
          }
        })
        .catch(err => {
          console.log(err)
          userInfo.status = !userInfo.status
          this.$message.error(err)
        })
    },
    // 显示添加用户对话框
    showCreateUserDialog() {
      this.dialogTitle = '添加用户'
      this.createUserInfo = true
      this.getRoleList()
      this.userInfoDialogVisible = true
    },
    // 关闭dialog后操作
    closeDialog() {
      this.userInfoForm = {}
      this.$refs.userInfoRef.resetFields()
    },
    // 新建或编辑用户
    createOrEditUser() {
      this.$refs.userInfoRef.validate(valid => {
        if (valid) {
          // 新建用户
          if (this.createUserInfo) {
            this.$http
              .post('/auth/register', this.userInfoForm)
              .then(res => {
                const resData = res.data
                if (resData.code === 2001) {
                  this.$message.success(resData.msg)
                  this.getUserList()
                  this.userInfoDialogVisible = false
                } else {
                  return this.$message.error(resData.msg)
                }
              })
              .catch(err => {
                return this.$message.error(err)
              })
          } else {
            // 编辑用户
            this.$http
              .post('/auth/update', this.userInfoForm)
              .then(res => {
                console.log(res)
                const resData = res.data
                if (resData.code === 2001) {
                  this.getUserList()
                  this.userInfoDialogVisible = false
                  this.$message.success(resData.msg)
                } else {
                  return this.$message.error(resData.msg)
                }
              })
              .catch(err => {
                return this.$message.error(err)
              })
          }
        }
      })
    },
    // 显示编辑用户对话框
    showEditUserDialog(id) {
      this.dialogTitle = '编辑用户'
      this.createUserInfo = false
      this.getRoleList()
      this.$http
        .get(`/auth/getById?id=${id}`)
        .then(res => {
          const resData = res.data
          if (resData.code === 200) {
            this.userInfoForm = resData.data[0]
          }
        })
        .catch(err => {
          this.$message.error(err)
        })
      this.userInfoDialogVisible = true
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http
            .get(`/auth/delete?id=${id}`)
            .then(res => {
              const resData = res.data
              if (resData.code === 200) {
                this.getUserList()
                return this.$message.success(resData.msg)
              } else {
                return this.$message.error(resData.msg)
              }
            })
            .catch(err => {
              return this.$message.error(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      console.log('delete user' + id)
    },
    // 查询用户
    searchUser() {
      this.$http
        .get(`/auth/search?query=${this.query}`)
        .then(res => {
          const resData = res.data
          if (resData.code === 200) {
            this.userList = resData.data.list
            this.$message.success(resData.msg)
          } else {
            this.$message.error(resData.msg)
          }
        })
        .catch(err => {
          this.$message.error(err)
        })
    },
    // 清楚搜索条件操作
    removeSearch() {
      this.getUserList()
    },
    // 获取权限列表
    getRoleList() {
      this.$http
        .get('/sys/role/getList')
        .then(res => {
          const resData = res.data
          if (resData.code === 200) {
            this.roleList = resData.data
          } else {
            return this.$message.error(resData.msg)
          }
        })
        .catch(err => {
          return this.$message.error(err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
@import './Users.less';
</style>
